﻿using MaterialDesignColors.Recommended;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace MyMeeting.Common
{
    public class NineGridPanel:WrapPanel
    {
        public NineGridPanel()
        {
            this.Orientation = Orientation.Horizontal;
            this.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            this.VerticalAlignment = System.Windows.VerticalAlignment.Center;
         
        }
        private int minW = 160;
        private int minH = 90;
        private double radio = 16.0/9;

        public int VisualCounts => this.Children.Count;

        public Brush lightGreen = Brushes.LightGreen;
        public Brush darkRed = Brushes.DarkRed;

        public void AddVideoVisual(Button visual)
        {
            if(VisualCounts%2==0)
            {
                visual.Background= darkRed;
            }
            else
            {
                visual.Background = lightGreen;
            }
            visual.Content = VisualCounts + 1;
            this.Children.Add(visual);
            CalculateSize();

        }
        private void CalculateSize()
        {
            var pw = this.Width;
            var ph = this.Height;
            var rows=VisualCounts;
            var maxH = Double.MinValue;
            var h = this.Height;
            while(rows >= 1)
            {
                var eh = h / rows;
                var ew=eh*radio;
                var eachRowCount = (int)(Math.Ceiling(VisualCounts * 1.0 / rows));
                if(ew*eachRowCount<=pw)
                {
                    maxH = Math.Max(maxH, eh);
                }
                rows -= 1;
            }

            var maxW = maxH * radio;

            foreach(Button v in this.Children)
            {
                v.Width = maxW;
                v.Height = maxH;
            }
           
        }
    }
}
